<template>
  <div class="xyt-talk-win-list">
    <div class="xyt-header" @click="close">
      <div class="xyt-online-num">在线人数：{{ online_num }}</div>
      <div class="flex-1">匿名聊天池</div>
      <img class="xyt-fj-home" src="../assets/img/fjdt.png" alt="" @click="goHome">
    </div>
    <div class="xyt-tips">只保留2小时内消息</div>
    <div class="xyt-talk-win" ref="talkWin">
      <img src="../assets/img/bj.png" class="bg" alt="">
      <van-pull-refresh v-model="loading" @refresh="onRefresh">
        <div ref="chatListBox" class="xyt-chat-list">
          <van-loading class="xyt-loading" v-if="chatList.length === 0 && loading" type="spinner" />
          <template v-for="(chat, index) in chatList" :key="index">
            <div v-if="chat.type === 'time'" class="xyt-talk-time-box">
              <div class="xyt-talk-time">{{ chat.time }}</div>
            </div>
            <div v-else-if="chat.type === 'message' && chat.id === userInfoStore.userInfo.external_user_id" class="xyt-talk-win-own">
              <div class="message-box">
                <div class="name">{{ chat.name }}</div>
                <div class="flex-1">{{ chat.content }}</div>
              </div>
              <div class="avatar">
                <img :src="chat.avatar || '/assets/avatar.png'" alt="">
              </div>
            </div>
            <div v-else class="xyt-talk-win-other">
              <div class="avatar">
                <img :src="chat.avatar || '/assets/avatar.png'" alt="">
              </div>
              <div class="message-box">
                <div class="name">{{ chat.name }}</div>
                <div class="flex-1">
                  {{ chat.content }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </van-pull-refresh>
    </div>
    <div class="xyt-reply-box flex">
      <div class="flex-1">
        <van-field v-model="replyContent" placeholder="说说你想说的~"></van-field>
      </div>
      <div>
        <van-button type="success" @click="sendMessage">发送</van-button>
      </div>
    </div>
    <div class="xyt-reply-box-wrapper" v-if="!userInfoStore.isAttention" @click="openTaskMessage"></div>
    <Attention ref="attentionDialog" position="center"></Attention>
  </div>
</template>
<script setup>
import Attention from './../components/Attention.vue'
import { useRouter, useRoute } from "vue-router"
import { useUserInfo } from './../stores/userInfo.js'
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue';
import { queryChatMsgs, addChatMsg, queryUserAnChatMember } from './../api/fly.js'
import { ws, joinRoom, getMessageTime, share, leaveRoom } from './../utils/utils.js'
import useWs from '../utils/useWs';

const attentionDialog = ref(null)
const router = useRouter()
const route = useRoute()

let userInfoStore = useUserInfo()
let show = ref(false)
let chat = ref({
  id: '10000'
})
let form = reactive({
  page_no: 1,
  page_size: 50,
  chat_id: '',
  create_time_begin: ''
})

let chatList = ref([])
let replyContent = ref('')
let loading = ref(false)
let talkWin = ref()
let chatListBox = ref()
let isBegin = true
let baseTime = new Date().getTime()
let online_num = ref(0)
let onlinePerson = ref([])
useWs({
  systemPushMessage: systemPushMessage
})

setInterval(() => {
  getOnlineNum()
}, 60000);

function openTaskMessage() {
  attentionDialog.value.open()
}

function onRefresh() {
  getChatList()
}

async function open() {
  form.page_no = 1
  chatList.value.length = 0
  show.value = true
  if (!userInfoStore.userInfo) {
    userInfoStore.setUserInfo(JSON.parse(sessionStorage.getItem("userInfo")))
  }
  ws && ws.on('CHAT_MSG', wsChatMsg)
  joinRoom(chat.value.id)
  getChatList()
  if (userInfoStore.isAttention) {
    await queryUserAnChatMember()
  }
}
function close() {
  ws && ws.off('CHAT_MSG', wsChatMsg)
  show.value = false
}
defineExpose({
  open
})

function systemPushMessage(data) {
  switch (data.reason) {
    case 'USER_JOIN_ROOM':
      if (data.body.external_user_id !== userInfoStore.userInfo.external_user_id) {
        let index = onlinePerson.value.indexOf(data.body.external_user_id)
        if (index === -1) {
          onlinePerson.value.push(data.body.external_user_id)
          online_num.value += 1
        }
      }
      break;
    case 'USER_LEAVE_ROOM':
      if (data.body.external_user_id !== userInfoStore.userInfo.external_user_id) {
        let index = onlinePerson.value.indexOf(data.body.external_user_id)
        if (index !== -1) {
          onlinePerson.value.splice(index, 1)
          online_num.value -= 1
        }
      }
      break;
  
    default:
      break;
  }
}

async function getOnlineNum() {
  const res = await queryChatMsgs(form)
  onlinePerson.value.length = 0
  res.result.online_user_ids && res.result.online_user_ids.forEach(userId => {
    onlinePerson.value.push(userId)
  });
  if (!onlinePerson.value.includes(userInfoStore.userInfo.external_user_id)) {
    onlinePerson.value.push(userInfoStore.userInfo.external_user_id)
  }
  online_num.value = onlinePerson.value.length
}

async function getChatList() {
  form.chat_id = chat.value.id
  form.create_time_begin = new Date().getTime() - 7200000
  loading.value = true
  const res = await queryChatMsgs(form)
  loading.value = false
  form.page_no += 1
  for (let i = 0; i < res.result.items.length; i++) {
    const item = res.result.items[i];
    let time = getMessageTime(item.create_time, baseTime)
    if (time) {
      baseTime = item.create_time
      chatList.value.unshift({
        type: 'time',
        time: time,
      })
    }
    chatList.value.unshift({
      type: 'message',
      id: item.msg_by,
      avatar: item.icon_url,
      content: item.content,
      isFly: false,
      name: item.name
    })
  }
  baseTime = new Date().getTime()
  if (isBegin) {
    res.result.online_user_ids && res.result.online_user_ids.forEach(userId => {
      onlinePerson.value.push(userId)
    });
    if (!onlinePerson.value.includes(userInfoStore.userInfo.external_user_id)) {
      onlinePerson.value.push(userInfoStore.userInfo.external_user_id)
    }
    online_num.value = onlinePerson.value.length
    resizeWinOffsetHeight()
    isBegin = true
  }
}
// 发送消息
async function sendMessage() {
  const res = await addChatMsg({
    chat_id: chat.value.id,
    content: replyContent.value
  })
  replyContent.value = ''
}

// ws消息处理
function wsChatMsg(data) {
  if (data) {
    switch (data.reason) {
      case 'ADD':
        let time = getMessageTime(new Date().getTime(), baseTime)
        if (time) {
          baseTime = data.body.create_time
          chatList.value.push({
            type: 'time',
            time: time,
          })
        }
        chatList.value.push({
          type: 'message',
          id: data.body.msg_by,
          avatar: data.body.icon_url,
          content: data.body.content,
          isFly: false,
          name: data.body.name
        })
        resizeWinOffsetHeight()
        break;
    
      default:
        break;
    }
  }
}

function resizeWinOffsetHeight() {
  nextTick(() => {
    talkWin.value.scrollTop = chatListBox.value.clientHeight - talkWin.value.clientHeight
  })
}

function goHome() {
  router.push({
    path: '/pool'
  })
}

onMounted(() => {
  open()
  share({
    title: '象牙塔: 匿名聊天室',
    desc: '放心大胆说你想说的，大家都来匿名说~',
    link: location.href,
    imgUrl: 'https://miai-1310370640.cos.ap-shanghai.myqcloud.com/share_photo/niming.jpg',
    success: function (res) {
      // 设置成功
    },
    fail: function(error) {
      console.log('error', error)
    }
  })
})
onUnmounted(() => {
  ws && ws.off('CHAT_MSG', wsChatMsg)
  leaveRoom(chat.value.id)
})
</script>
<style lang="scss" scoped>
.xyt-talk-win-list {
  margin: auto;
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
  .xyt-header {
    position: relative;
    text-align: center;
    background-color: #fff;
    line-height: 40px;
    color: #333;
    padding: 0 10px;
    font-size: 15px;
    border-bottom: 1px solid #eee;
    .flex-1 {
      font-weight: bold;
    }
    .c-grey {
      color: #c5c5c5;
      font-size: 12px;
    }
  }
}
.xyt-talk-win {
  position: absolute;
  left: 0;
  top: 70px;
  right: 0;
  bottom: 45px;
  overflow: auto;
  .bg {
    position: fixed;
    left: 0;
    top: 41px;
    right: 0;
    bottom: 44px;
  }
}
.xyt-talk-winer {
  padding: 8px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  align-items: center;
  .flex-1 {
    padding-left: 8px;
  }
  .avatar {
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  .school {
    color: #999;
  }
  .status {
    color: #48cd8f;
    i {
      display: inline-block;
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #48cd8f;
      vertical-align: middle;
      margin-right: 6px;
    }
  }
}
.xyt-chat-list {}
.xyt-talk-win-own {
  padding: 8px;
  text-align: right;
  .avatar {
    display: inline-block;
    margin-left: 6px;
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  .message-box {
    display: inline-block;
    max-width: calc(100% - 120px);
    min-width: 100px;
    vertical-align: top;
    text-align: left;
    .name {
      text-align: right;
      color: #999;
      font-size: 14px;
      vertical-align: top;
    }
  }
  .flex-1 {
    padding: 8px;
    margin-left: 6px;
    background: #a9e87a;
    border-radius: 10px 0px 10px 10px;
    color: #333;
  }
}
.xyt-talk-win-other {
  padding: 8px 100px 8px 8px;
  .avatar {
    display: inline-block;
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      vertical-align: top;
    }
  }
  .message-box {
    display: inline-block;
    max-width: calc(100% - 120px);
    min-width: 100px;
    vertical-align: top;
    text-align: left;
    .name {
      text-align: left;
      color: #999;
      font-size: 14px;
      vertical-align: top;
    }
  }
  .flex-1 {
    text-align: left;
    background: #FFFFFF;
    border-radius: 0px 10px 10px 10px;
    padding: 8px;
    margin-left: 6px;
  }
}
.xyt-fly-tag {
  font-weight: bold;
  word-break: break-all;
}
.xyt-reply-box {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  border-top: 1px solid #f0f0f0;
}
.xyt-reply-box-wrapper {
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  height: 44px;
}
.xyt-tips {
  position: relative;
  z-index: 9;
  text-align: center;
  font-size: 12px;
  line-height: 32px;
}
.xyt-fj-home {
  position: absolute;
  top: 3px;
  right: 12px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
}
.xyt-online-num {
  position: absolute;
  top: 1px;
  left: 12px;
  width: 120px;
  font-size: 12px;
  color: #1C8CFE;
  text-align: left;
}
.xyt-talk-time-box {
  text-align: center;
}
.xyt-talk-time {
  display: inline-block;
  height: 16px;
  padding: 2px 8px;
  background: rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  text-align: center;
  font-size: 12px;
  line-height: 12px;
  color: #fff;
}
</style>